package com.example.its2021606134chh.DAModule;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
//import android.widget.CalendarView;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.BusDiyModule.BusDiyDateActivity;
import com.example.its2021606134chh.ETCModule.ETC_Car_Recharge;
import com.example.its2021606134chh.ETCModule.MySQLiteOpenHelper;
import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.TrafficViolationModule.CarSQLiteOpenHelper;
import com.example.its2021606134chh.TrafficViolationModule.TVVideoActivity;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DateTVFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DateTVFragment extends Fragment  implements    //CalendarView的导入接口
        com.haibin.calendarview.CalendarView.OnCalendarMultiSelectListener,
        com.haibin.calendarview.CalendarView.OnCalendarInterceptListener,
        com.haibin.calendarview.CalendarView.OnYearChangeListener,
        com.haibin.calendarview.CalendarView.OnMonthChangeListener,
        com.haibin.calendarview.CalendarView.OnCalendarSelectListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private LineChartView lineChart;
    public final static String[] xDate = {"北京路", "重庆路", "沈阳路", "南京路", "上海路", "广州路", "高速公路"}; //x
    //    String[] date = {"10-22","11-22","12-22","1-22","6-22","5-23","5-22","6-22","5-23","5-22"};//X轴的标注
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    private static final int FIRST = 0;
    private static final int SECOND = 1;
    private ImageView imgDateOpen;
    private Spinner spDate1;
    private Spinner spDate2;
    private CalendarView calendarView;
    private TextView tvDialogYear;
    private TextView tvDialogMonDay;
    private Date fTime = stringToDate("2016-01-01");
    private Date seTime = stringToDate("2017-01-01");
    private static final Date FTIME = stringToDate("2016-01-01");
    private static final Date SETIME = stringToDate("2017-01-31");
    private int[] score;

    public DateTVFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DateTVFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DateTVFragment newInstance(String param1, String param2) {
        DateTVFragment fragment = new DateTVFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_date_t_v, container, false);
        lineChart = (LineChartView) view.findViewById(R.id.lineChart);
        imgDateOpen = (ImageView) view.findViewById(R.id.imgDateOpen);
        spDate1 = (Spinner) view.findViewById(R.id.spDate1);
        spDate2 = (Spinner) view.findViewById(R.id.spDate2);

        // Inflate the layout for this fragment
        initDate();
        getAxisXLables();//获取x轴的标注
        getAxisPoints(score);//获取坐标点
        initLineChart();//初始化
        spDate1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dialog(FIRST);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spDate2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dialog(SECOND);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        imgDateOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getContext(), DateActivity.class);
//                Objects.requireNonNull(getActivity()).startActivity(intent);
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                View view2 = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_dialog_date,null,false);
                dialog.setView(view2);
                tvDialogYear = (TextView) view2.findViewById(R.id.tvDialogYear);
                tvDialogMonDay = (TextView) view2.findViewById(R.id.tvDialogMonDay);
                TextView tvDialogCancel = (TextView) view2.findViewById(R.id.tvDialogCancel);
                TextView tvDialogConfirm = (TextView) view2.findViewById(R.id.tvDialogConfirm);
                calendarView = (CalendarView) view2.findViewById(R.id.calendar);
                long start = FTIME.getTime();
                long end = SETIME.getTime();
                calendarView.setMaxMultiSelectSize(1);
                calendarView.setRange(2016, 1, 1, 2017, 1, 31);
                AlertDialog mdialog = dialog.show();
//                calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
//                    @SuppressLint("SetTextI18n")
//                    @Override
//                    public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
//                        String content, content2;
//                        tvDialogYear.setText(String.valueOf(year));
//                        if (month < 9) {
//                            if (dayOfMonth < 10) {
//                                content = year + "-0" + (month+1) + "-0" + dayOfMonth;
//                                if (month == 8) {
//                                    content2 = year + "-" + (month+2) + "-0" + dayOfMonth;
//                                } else {
//                                    content2 = year + "-0" + (month+2) + "-0" + dayOfMonth;
//                                }
//                            } else {
//                                content = year + "-0" + (month+1) + "-" + dayOfMonth;
//                                if (month == 8) {
//                                    content2 = year + "-" + (month+2) + "-" + dayOfMonth;
//                                } else {
//                                    content2 = year + "-0" + (month+2) + "-" + dayOfMonth;
//                                }
//                            }
//                        } else {
//                            if (dayOfMonth < 10) {
//                                content = year + "-" + (month+1) + "-0" + dayOfMonth;
//                                if (month < 11) {
//                                    content2 = year + "-" + (month+2) + "-0" + dayOfMonth;
//                                } else {
//                                    content2 = year + "-01" + "-0" + dayOfMonth;
//                                }
//                            } else {
//                                content = year + "-" + (month+1) + "-" + dayOfMonth;
//                                if (month < 11) {
//                                    content2 = year + "-" + (month+2) + "-" + dayOfMonth;
//                                } else {
//                                    content2 = year + "-01" + "-" + dayOfMonth;
//                                }
//                            }
//                        }
//                        tvDialogYear.setText(String.valueOf(year));
//                        SimpleDateFormat format = new SimpleDateFormat("E");
//                        Date date = stringToDate(content);
//                        String week = format.format(date);
//                        tvDialogMonDay.setText((month+1) + "月" + dayOfMonth + "日 " + week);
//                        Toast.makeText(getContext(), "开始日期:\n"+ content + "\n结束日期:\n" + content2, Toast.LENGTH_SHORT).show();
//                        fTime = stringToDate(content);
//                        seTime = stringToDate(content2);
//                    }
//                });
                tvDialogConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initDate();
                        getAxisXLables();//获取x轴的标注
                        getAxisPoints(score);//获取坐标点
                        initLineChart();//初始化
                        mdialog.dismiss();
                    }
                });
                tvDialogCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mdialog.dismiss();
                    }
                });
            }
        });
        return view;
    }

    private void initDate() {
        CarSQLiteOpenHelper openHelper;
        SQLiteDatabase database;
        openHelper = new CarSQLiteOpenHelper(getContext(), "CarPeccancy.db", null, 1);
        database = openHelper.getReadableDatabase();
        Set<String> stringSet = new HashSet<String>();
        Map<String, Integer> stringMap = new HashMap<String, Integer>();
        List<String> addrs = new ArrayList<String>();
        String sAddr;
        try (Cursor cursor = database.query("carpeccancy", null, null, null, null, null, null)) {
            if (cursor.moveToFirst()) {
                do {
                    String pdatetime = cursor.getString(2);
                    String paddr = cursor.getString(3);
                    String sTime = pdatetime.substring(0, 10);
                    Date Time = stringToDate(sTime);
                    long test = Time.getTime();
                    long start = fTime.getTime();
                    long end = seTime.getTime();
//                    Log.i("TAG", sTime + " " + Long.compare(test, end));
                    if (Long.compare(test, start) != -1 && Long.compare(test, end) != 1) {
                        addrs.add(paddr);
                    }
                } while (cursor.moveToNext());
            }
        } catch (SQLException ignored) {
            Toast.makeText(getContext(), "没有查询到违章数据！", Toast.LENGTH_SHORT).show();
        } finally {
            database.close();
        }

        for (int i = 0; i < addrs.size(); i++) {
            sAddr = addrs.get(i);
            if (stringSet.contains(sAddr)) {
                stringMap.put(sAddr, stringMap.get(sAddr) + 1);
            } else {
                stringSet.add(sAddr);
                stringMap.put(sAddr, 1);
            }
        }

        int a1 = 0;
        int a2 = 0;
        int a3 = 0;
        int a4 = 0;
        int a5 = 0;
        int a6 = 0;
        int a7 = 0;
        for (String s : stringSet) {
            try {
                if (stringMap.get(s) != null) {
                    switch (s) {
                        case "北京路":
                            a1 = stringMap.get(s);
                            break;
                        case "重庆路":
                            a2 = stringMap.get(s);
                            break;
                        case "沈阳路":
                            a3 = stringMap.get(s);
                            break;
                        case "南京路":
                            a4 = stringMap.get(s);
                            break;
                        case "上海路":
                            a5 = stringMap.get(s);
                            break;
                        case "广州路":
                            a6 = stringMap.get(s);
                            break;
                        case "高速公路":
                            a7 = stringMap.get(s);
                    }
                }
            } catch (NullPointerException e) {
                Log.i("TAG", "NullPointerException");
            }


        }
        score = new int[]{a1, a2, a3, a4, a5, a6, a7};
    }

    private void dialog(int num) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        View view2 = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_date_dialog,null,false);
        dialog.setView(view2);
        TextView tvDialYear = (TextView)view2.findViewById(R.id.tvDialYear);
        TextView tvDialMon = (TextView)view2.findViewById(R.id.tvDialMon);
        TextView tvDialDay = (TextView)view2.findViewById(R.id.tvDialDay);
        TextView tvDateCancel = (TextView)view2.findViewById(R.id.tvDateCancel);
        TextView tvDateSave = (TextView)view2.findViewById(R.id.tvDateSave);
        Spinner spYear = (Spinner)view2.findViewById(R.id.spYear);
        Spinner spMonth = (Spinner)view2.findViewById(R.id.spMonth);
        Spinner spDay = (Spinner)view2.findViewById(R.id.spDay);
        tvDialYear.setText(spYear.getSelectedItem().toString());
        tvDialMon.setText(spMonth.getSelectedItem().toString());
        tvDialDay.setText(spDay.getSelectedItem().toString());
        spYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tvDialYear.setText(spYear.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spMonth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tvDialMon.setText(spMonth.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        spDay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tvDialDay.setText(spDay.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        AlertDialog mdialog = dialog.show();
        tvDateSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sYear = spYear.getSelectedItem().toString();
                String sMonth = spMonth.getSelectedItem().toString();
                String sDay = spDay.getSelectedItem().toString();
                String sTime = sYear + "-" + sMonth + "-" + sDay;
                //初始化
                //获取坐标点
                //获取x轴的标注
                if (num == 0) {
                    fTime = stringToDate(sTime);
                } else {
                    seTime = stringToDate(sTime);
                }
                initDate();
                getAxisXLables();//获取x轴的标注
                getAxisPoints(score);//获取坐标点
                initLineChart();//初始化
//                String sTest = dateToStrLong(time);
//                Log.i("TAG", sTest);
                mdialog.dismiss();
            }
        });
        tvDateCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mdialog.dismiss();
            }
        });
    }


    /**
     * 初始化LineChart的一些设置
     */
    private void initLineChart() {
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(false);//曲线是否平滑
//	    line.setStrokeWidth(3);//线条的粗细，默认是3
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//		line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
//        axisX.setHasTiltedLabels(true);  //X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
//	    axisX.setTextColor(Color.WHITE);  //设置字体颜色
        axisX.setTextColor(Color.parseColor("#D6D6D9"));//灰色

//	    axisX.setName("未来几天的天气");  //表格名称
        axisX.setTextSize(11);//设置字体大小
//        axisX.setMaxLabelChars(7); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
//	    data.setAxisXTop(axisX);  //x 轴在顶部
//        axisX.setHasLines(true); //x 轴分割线


        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(11);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边
        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(true);
        lineChart.setZoomType(ZoomType.HORIZONTAL);  //缩放类型，水平
        lineChart.setMaxZoom((float) 3);//缩放比例
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);
        Viewport v = new Viewport(lineChart.getMaximumViewport());
        lineChart.setCurrentViewport(v);
    }

    /**
     * X 轴的显示
     */
    private void getAxisXLables() {
        mAxisXValues.clear();
        for (int i = 0; i < xDate.length; i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(xDate[i]));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints(int[] score) {
        mPointValues.clear();
        for (int i = 0; i < score.length; i++) {
            mPointValues.add(new PointValue(i, score[i]));
        }
    }

    public static Date stringToDate(String dateString){
        ParsePosition position = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(dateString,position); //将字符串转换为Date日期格式
    }

    public static String dateToStrLong(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    @Override
    public boolean onCalendarIntercept(Calendar calendar) {
        int day = calendar.getDay();
        return calendar.getYear()<= calendarView.getCurYear() &&
                calendar.getMonth() <= calendarView.getCurMonth() &&
                calendar.getDay() < calendarView.getCurDay();
    }

    @Override
    public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {
        Toast.makeText(getActivity(),
                calendar.toString() + (isClick ? "拦截不可点击" : "拦截设定为无效日期"),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCalendarMultiSelectOutOfRange(Calendar calendar) {
        Log.e("OutOfRange", "OutOfRange" + calendar);
    }

    @Override
    public void onMultiSelectOutOfSize(Calendar calendar, int maxSize) {
        Toast.makeText(getActivity(), "超过最大选择数量 ：" + maxSize, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCalendarMultiSelect(Calendar calendar, int curSize, int maxSize) {
        Log.e("onDateSelected", "  -- " + calendar.getYear() +
                "  --  " + calendar.getMonth() +
                "  -- " + calendar.getDay() +
                "  --  " + "  --   " + calendar.getScheme());

        String content, content2;
        int year = calendar.getYear();
        int month = calendar.getMonth();
        int dayOfMonth = calendar.getDay();
        if (month < 9) {
            if (dayOfMonth < 10) {
                content = year+"-0"+month+"-0"+dayOfMonth;
                content2 = year+"-0"+(month+1)+"-0"+dayOfMonth;
            } else {
                content = year+"-0"+month+"-"+dayOfMonth;
                content2 = year+"-0"+(month+1)+"-"+dayOfMonth;
            }
        } else if (month < 12){
            if (dayOfMonth < 10) {
                content = year+"-"+month+"-0"+dayOfMonth;
                content2 = year+"-"+(month+1)+"-0"+dayOfMonth;
            } else {
                content = year+"-"+month+"-"+dayOfMonth;
                content2 = year+"-"+(month+1)+"-"+dayOfMonth;
            }
        } else {    //12
            if (dayOfMonth < 10) {
                content = year+"-"+month+"-0"+dayOfMonth;
                content2 = (year+1)+"-01"+"-0"+dayOfMonth;
            } else {
                content = year+"-"+month+"-"+dayOfMonth;
                content2 = (year+1)+"-01"+"-"+dayOfMonth;
            }
        }
        Toast.makeText(getActivity(), "你选择了:\n"+content, Toast.LENGTH_SHORT).show();
        tvDialogYear.setText(String.valueOf(year));
        SimpleDateFormat format = new SimpleDateFormat("E");
        Date date = stringToDate(content);
        String week = format.format(date);
        tvDialogMonDay.setText((month+1) + "月" + dayOfMonth + "日 " + week);
        Toast.makeText(getContext(), "开始日期:\n"+ content + "\n结束日期:\n" + content2, Toast.LENGTH_SHORT).show();
        fTime = stringToDate(content);
        seTime = stringToDate(content2);
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        Log.e("onDateSelected", "  -- " + calendar.getYear() +
                "  --  " + calendar.getMonth() +
                "  -- " + calendar.getDay() +
                "  --  " + isClick + "  --   " + calendar.getScheme());
    }

    @Override
    public void onMonthChange(int year, int month) {
        Log.e("onMonthChange", "  -- " + year + "  --  " + month);
    }

    @Override
    public void onYearChange(int year) {
        Log.i("onYearChange", "  -- " + year);
    }
}
